/*
 * Copyright 2017 Baiyyy
 * @(#)HttpUtils.java
 */

package com.byyy.ccts.core.utils.http;

import com.byyy.ccts.core.base.ILogBase;
import com.byyy.ccts.core.utils.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;


/**
 * @fileName HttpUtils.java
 * @description
 */
public class HttpUtils implements ILogBase {

	/**
	 * HTTP GET请求
	 * @param url
	 * @param param
	 * @return
	 */
    public static String get(String url, String param) {
        StringBuffer responseInfo = new StringBuffer();
        BufferedReader br = null;
        InputStreamReader is = null;
        String line = null;
		// 请求参数（paramName1=paramValue1&paramName2=paramValue2）
        String urlParam = url + (!StringUtils.isEmpty(param) ? ("?" + param) : "");
        try {

            URLConnection urlc = new URL(urlParam).openConnection();
            // 设置通用的请求属性
            urlc.setRequestProperty("accept", "*/*");
            urlc.setRequestProperty("connection", "Keep-Alive");
            // 建立实际的连接
            urlc.connect();
            /*
             * 获取请求响应头信息
             */
            Map<String, List<String>> headerFields = urlc.getHeaderFields();
            for (String key : headerFields.keySet()) {
                // log.debug("HTTPRequestUtil发送GET请求响应头." + key + "=" +
                // headerFields.get(key));
            }

            // 定义 BufferedReader输入流读取响应
            is = new InputStreamReader(urlc.getInputStream(), "UTF-8");
            br = new BufferedReader(is);
            while ((line = br.readLine()) != null) {
                responseInfo.append(line);
            }

        } catch (Exception e) {
            logger.error("Http Get 请求异常！", e);
        } finally {

            try {
                if (br != null) {
                    br.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return responseInfo.toString();
    }

	/**
	 * HTTP POST请求
	 * @param url
	 * @param param
	 * @return
	 */
    public static String post(String url, String param) {
        StringBuffer responseInfo = new StringBuffer();
        PrintWriter pw = null;
        BufferedReader br = null;
        InputStreamReader isr = null;
        String line = null;
        try {
            // 打开连接
            URLConnection urlc = new URL(url).openConnection();
            HttpURLConnection httpUrlc = (HttpURLConnection) urlc;
            // 设置通用的请求属性
            httpUrlc.setRequestProperty("accept", "*/*");
            httpUrlc.setRequestProperty("connection", "Keep-Alive");
            httpUrlc.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
            httpUrlc.setRequestProperty("Charset", "UTF-8");
            // 发送POST请求必须设置
            httpUrlc.setDoOutput(true);
            httpUrlc.setDoInput(true);
            httpUrlc.setRequestMethod("POST");
            // 获取URLConnection对象对应的输出流
            pw = new PrintWriter(httpUrlc.getOutputStream());
            // 发送请求参数（paramName1=paramValue1&paramName2=paramValue2）
            pw.print(param);
            // Flush输出流的缓冲
            pw.flush();
            /*
             * 获取请求响应头信息
             */
            Map<String, List<String>> headerFields = httpUrlc.getHeaderFields();
            for (String key : headerFields.keySet()) {
                // headerFields.get(key));
            }

            // 定义BufferedReader输入流读取响应
            isr = new InputStreamReader(httpUrlc.getInputStream(), "UTF-8");
            br = new BufferedReader(isr);

            while ((line = br.readLine()) != null) {
                responseInfo.append(line);
            }
        } catch (Exception e) {
            logger.error("Http Post 请求异常！", e);
        } finally {
            try {
                if (pw != null) {
                    pw.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
            }
        }

        return responseInfo.toString();
    }

    /**
     * HTTP POST JSON请求
     * @param url
     * @param jsonParam
     * @return
     */
    public static String postWithJson(String url, String jsonParam) {
        return HttpUtils.postWithJson(url, jsonParam, null);
    }

	/**
	 * HTTP POST JSON WITH HEADER
	 * @param url
	 * @param jsonParam
	 * @param header
	 * @return
	 */
    public static String postWithJson(String url, String jsonParam, Map<String, String> header) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost method = new HttpPost(url);
        String body = null;

        // 处理请求
        if (method != null & jsonParam != null
                && !"".equals(jsonParam.trim())) {
            try {

                method.addHeader("Content-type",
                        "application/json; charset=utf-8");
                method.setHeader("Accept", "application/json");
                if (header != null) {
                    for (String headKey : header.keySet()) {
                        method.setHeader(headKey, header.get(headKey));
                    }
                }
                method.setEntity(
                        new StringEntity(jsonParam, Charset.forName("UTF-8")));

                HttpResponse response = httpClient.execute(method);

                // Read the response body
                body = EntityUtils.toString(response.getEntity());
                //乱码问题
                //	body = new String(body.getBytes("ISO8859-1"), "UTF-8");
            } catch (IOException e) {
                logger.error("Http postWithJson 请求异常！", e);
            }
        }
        return body;
    }

    /**
     * HTTP POST JSON WITH HEADER
     * @param url
     * @param jsonParam
     * @return
     */
    public static byte[] postWithJsonRetBytes(String url, String jsonParam) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost method = new HttpPost(url);
        byte[] body = null;

        // 处理请求
        if (method != null & jsonParam != null
                && !"".equals(jsonParam.trim())) {
            try {

                method.addHeader("Content-type",
                        "application/json; charset=utf-8");
                method.setHeader("Accept", "application/json");
                method.setEntity(
                        new StringEntity(jsonParam, Charset.forName("UTF-8")));

                HttpResponse response = httpClient.execute(method);

                // Read the response body
                body = EntityUtils.toByteArray(response.getEntity());
                //乱码问题
                //	body = new String(body.getBytes("ISO8859-1"), "UTF-8");
            } catch (IOException e) {
                logger.error("Http postWithJson 请求异常！", e);
            }
        }
        return body;
    }

    /**
     * HTTPS GET请求
     * @param url
     * @return
     */
    public static String getHttps(String hostname, String url) {
        SSLHttpClient sslHttpClient = new SSLHttpClient();
        HttpClient httpClient = null;
        String result = null;
        try {
            httpClient = sslHttpClient.registerSSL(hostname, "TLS", 443, "https");
        } catch (Exception e) {
            logger.error("构建HTTPS请求异常！", e);
        }
        HttpGet get = new HttpGet(url);
        try {
            HttpResponse response = httpClient.execute(get);
            if (response != null) {
                if (200 == response.getStatusLine().getStatusCode()) {
                    HttpEntity httpEntity = response.getEntity();
                    if (httpEntity != null) {
                        result = EntityUtils.toString(httpEntity, "UTF-8");
                    }
                }
                else {
                    logger.error("Https Get 请求失败！");
                }
            }

        } catch (Exception e) {
            logger.error("Https Get 请求异常！", e);
        } finally {

        }
        return result;
    }

    /**
     * HTTPS POST JSON请求
     * @param url
     * @param jsonParam
     * @return
     */
    public static String httpsPostWithJson(String hostname, String url, String jsonParam) {
        return HttpUtils.httpsPostWithJson(hostname, url, jsonParam, null);
    }

    /**
     * HTTPS POST JSON WITH HEADER
     * @param url
     * @param jsonParam
     * @param header
     * @return
     */
    public static String httpsPostWithJson(String hostname, String url, String jsonParam, Map<String, String> header) {
        SSLHttpClient sslHttpClient = new SSLHttpClient();
        HttpClient httpClient = null;
        try {
            httpClient = sslHttpClient.registerSSL(hostname, "TLS", 443, "https");
        } catch (Exception e) {
            logger.error("构建HTTPS请求异常！", e);
        }
        HttpPost method = new HttpPost(url);
        String body = null;


        // 处理请求
        if (method != null & jsonParam != null
                && !"".equals(jsonParam.trim())) {
            try {

                method.addHeader("Content-type",
                        "application/json; charset=utf-8");
                method.setHeader("Accept", "application/json");
                if (header != null) {
                    for (String headKey : header.keySet()) {
                        method.setHeader(headKey, header.get(headKey));
                    }
                }
                method.setEntity(
                        new StringEntity(jsonParam, Charset.forName("UTF-8")));


                HttpResponse response = httpClient.execute(method);

                // Read the response body
                body = EntityUtils.toString(response.getEntity());
                //乱码问题
                //	body = new String(body.getBytes("ISO8859-1"), "UTF-8");
            } catch (IOException e) {
                logger.error("Https postWithJson 请求异常！", e);
            }
        }
        return body;
    }

    private static HttpClientContext context = HttpClientContext.create();

    /**
     * 添加验证  在请求之前调用次方法；也可以不用调用此方法，通过请求头的方式验证
     *
     * @param username
     * @param password
     */
    public static void addUserOAuth(String username, String password) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        org.apache.http.auth.Credentials credentials = new org.apache.http.auth.UsernamePasswordCredentials(username, password);
        credsProvider.setCredentials(org.apache.http.auth.AuthScope.ANY, credentials);
        context.setCredentialsProvider(credsProvider);
    }

}
